/* 
 *	Written by Joe Freeman 10/91
 *	This program comes with no warrenty or copyright.
 *	Use at your own risk.  If you don't like it, fix it.
 *	Thats why you have the sources.
 *
 *	V1	27 lines of code
 *	V2	terminate instead of deactivate
 *	V3	hide instead of deactivate
 *
 */
 

#import "PasteBoardSaver.h"
#import <libc.h>
#import <appkit/Application.h>		/* NXApp */
#import <appkit/Pasteboard.h>
#import <appkit/SavePanel.h>
#import <appkit/Listener.h>	
#import <defaults.h>	

@implementation PasteBoardSaver

- appDidInit:sender
{
    [[NXApp appListener] setServicesDelegate:self];
    
    return self;
}

#define EPS 1
#define TIFF 2
#define ASCII 3
#define RTF 4

- pbToFile:pb
	userData:(const char *)uDat
	error:(char **)aMsg
{
    const NXAtom *types;
    char *data;
    int length;
    int	requested;
    NXStream *memStream;
    id savePanel = [SavePanel new];

    requested = atoi(uDat) ;
    types = [pb types];
    while (types && *types){
    	if (requested == EPS && *types == NXPostScriptPboardType) {
			[savePanel setRequiredFileType:"eps"];
			break;
	} else if (requested == TIFF  && *types == NXTIFFPboardType){
		[savePanel setRequiredFileType:"tiff"];
		break;
	} else if (requested == ASCII && *types == NXAsciiPboardType){
		[savePanel setRequiredFileType:""];
		break;
	} else  if (requested == RTF && *types == NXRTFPboardType){
		[savePanel setRequiredFileType:"rtf"];
		break;
	}  
	types++;
    }
    
    if (types && *types){
	/* need to get the data out of the pasteboard */
	[pb readType:*types data:&data length:&length];
	
	/* open up save panel, ask for a place to put it and put it there */
	if ([savePanel runModal]){
		memStream = NXOpenMemory(NULL, 0, NX_WRITEONLY);
		NXWrite(memStream, data, length);
		NXSaveToFile(memStream, [savePanel filename]);
		NXCloseMemory(memStream, NX_FREEBUFFER);
		/* everyone hated the fact the old app didn't come back */
	} else {
		//strcpy(*aMsg, "User aborted pasteboard save.");
	}
    }
    if ( NXGetDefaultValue([NXApp appName], "HangAround"))
    	[NXApp hide:self];
    else
	[NXApp perform:@selector(terminate:) 
			with:self 
			afterDelay: 1
			cancelPrevious:YES];
    return self;
}



@end
